<template>
  <div class="view-container">
    <div class="main-content">
      <div class="list-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <div class="filter-container">
            <el-row :gutter="40" style="margin:0px;">
              <el-col :lg="24">
                <el-form :inline="true" :model="filterData" label-position="right" size="small"
                  class="filter-form-inline">
                  <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
                    <el-col :lg="5" :xs="4">
                      <el-form-item label="审批类型" style="width: 100%">
                        <el-select v-model="filterData.processDefinitionKey" clearable style="width: 100%"
                          placeholder="请选择审批类型" @change="listSearch">
                          <el-option v-for="item in dictMap?.approval_type" :key="item.id" :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="5" :xs="4">
                      <el-form-item label="关键字" style="width: 100%">
                        <el-input v-model="filterData.keyWord" clearable placeholder="流程编号，信息摘要" />
                      </el-form-item>
                    </el-col>
                    <el-col :lg="5" :xs="4">
                      <el-form-item :label="label" style="width: 100%">
                        <date-range-picker v-model:date="date" style="width: 100%" type="daterange" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" @change="handlDate" />
                      </el-form-item>
                    </el-col>
                    <el-col v-if="activeName==='COMPLETED'" :lg="5" :xs="4">
                      <el-form-item label="状态" style="width: 100%">
                        <el-select v-model="filterData.processInstanceConclusion" clearable style="width: 100%"
                          placeholder="请选择审批状态">
                          <el-option v-for="item in dictMap?.endtask" :key="item.id" :label="item.label"
                            :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="4" :xs="4">
                      <el-form-item style="width: 100%">
                        <el-button class="border-btn" @click="handlReact">重置</el-button>
                        <el-button type="primary" class="main-btn" @click="handlSearch">搜索</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-col>
            </el-row>
          </div>
          <el-tab-pane label="进行中" name="ACTIVE" />
          <el-tab-pane label="已结束" name="COMPLETED" />
        </el-tabs>
        <table-view header-cell-class-name="table-header" :data="listData" border :cell-style="cellStyle"
          @sort-change="handlSort" @row-click="rowClick">
          <el-table-column prop="processNo" label="流程编号" fixed="left" :min-width="140" header-align="center" />

          <el-table-column :min-width="180" prop="processDefinitionName" label="流程审批类型" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column :min-width="450" prop="abstract" label="信息摘要" header-align="center"
            :show-overflow-tooltip="true" />
          <el-table-column label="发起时间" sortable="custom" :min-width="170" align="center">
            <template #default="scope">
              <span> {{ dateFormat('yyyy-mm-dd HH:MM', scope.row.startTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最后处理时间" sortable="custom" :min-width="170" align="center">
            <template #default="scope">
              <span v-if="scope.row.lastTask?.endTime">
                {{ dateFormat('yyyy-mm-dd HH:MM', scope.row.lastTask?.endTime) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column v-if="activeName==='ACTIVE'" :min-width="120" label="当前审批节点" header-align="center"
            align="center">
            <template #default="scope">
              <!--              <div>-->
              <!--                {{ scope.row.currentTask?.taskName }}-->
              <!--              </div>-->
              <div v-if="scope.row.currentTask?.taskAssignee">
                <i class="iconfont icon-user" style="font-size:14px" />
                <span style="margin-left:4px;">{{ scope.row.currentTask?.taskAssignee }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :min-width="100" label="状态" header-align="center" align="center" fixed="right">
            <template #default="scope">
              <div v-if="activeName==='ACTIVE'" class="status">
                <div v-if="scope.row.processInstanceStatus==='ACTIVE'" class="status-item">
                  <div style="line-height: 20px">进行中</div>
                  <div v-if="scope.row.processInstanceConclusion==='REJECT_INITIATOR'" style="line-height: 20px"
                    class="flow-status-color">[ 回退 ]
                  </div>
                </div>
              </div>
              <div v-else-if="activeName==='COMPLETED'" class="status">
                <span>{{ getLabel('approval_result', scope.row.processInstanceConclusion) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="activeName==='ACTIVE'" :min-width="140" label="操作" header-align="center" fixed="right">
            <template #default="scope">

              <el-button v-auth="{v:['crm:audit:myStarted:undo'],bool:scope.row.whetherCancel}" type="text"
                @click="cancelOperation(scope.row)">撤销</el-button>

              <el-button v-auth="{v:['crm:audit:myStarted:approval'],bool:scope.row.currentTask?.allow}" type="text"
                @click="auditOperation(scope.row)">审批
              </el-button>
            </template>
          </el-table-column>
        </table-view>
        <Pagination v-model:page="filterData.page" v-model:limit="filterData.pageSize"
          style="display: flex; justify-content: flex-end" :total="total" @pagination="refreshList" />
      </div>
    </div>
    <!-- 审批弹框 -->
    <approval-dialog ref="approvalRef" @succsess="refreshList" />
  </div>
</template>

<script>
import {getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from "vue";
import {useRouter} from "vue-router";
import {crmStore} from "@CRM/store";

export default {
  setup(props, context) {
    const api = inject("api");
    const router = useRouter();
    const currentInstance = getCurrentInstance();
    var approvalRef = ref(null);
    var reactiveData = reactive({
      activeName: "ACTIVE",
      listData: [],
      total: 0,
      dictMap: crmStore.getters["dictionary/getDictionary"],
      filterData: {
        status: "ACTIVE",
        keyWord: "",
        page: 1,
        pageSize: 20,
        initiatorStartTime: null, // 发起开始时间
        initiatorEndTime: null, // 发起结束时间
        manageStartTime: null, // 处理开始时间
        manageEndTime: null, // 处理结束时间
        processDefinitionKey: "",
        processInstanceConclusion: "",
      },
      date: "",
      label: "发起时间",
    });

    const handlDate = (val) => {
      console.log(val, "---------");
      if (val) {
        if (reactiveData.activeName === "ACTIVE") {
          reactiveData.filterData.initiatorStartTime = val[0];
          reactiveData.filterData.initiatorEndTime = val[1];
        }
        if (reactiveData.activeName === "COMPLETED") {
          reactiveData.filterData.manageStartTime = val[0];
          reactiveData.filterData.manageEndTime = val[1];
        }
      }
    };

    const handlSearch = () => {
      reactiveData.filterData.page = 1;
      getList(reactiveData.filterData);
    };

    const handlReact = () => {
      reactiveData.filterData = {
        status: reactiveData.activeName,
        processDefinitionKey: "",
        keyWord: "",
        page: 1,
        pageSize: 20,
        initiatorStartTime: null, // 发起开始时间
        initiatorEndTime: null, // 发起结束时间
        manageStartTime: null, // 处理开始时间
        manageEndTime: null, // 处理结束时间
        processInstanceConclusion: "",
      };
      reactiveData.date = "";
      getList(reactiveData.filterData);
    };

    const cellStyle = (row) => {
      if (row.column.label === "操作") return;
      return "cursor: pointer;";
    };
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event);
      if (column.label === "操作") return;
      router.push({
        name: "myStartedDetail",
        query: {
          id: row.processInstanceId,
          serviceKey: row.serviceKey,
          type: row.processDefinitionKey,
          taskId: row.currentTask?.taskId,
          xmlId: row?.processDefinitionId,
        },
      });
    };
    const handleClick = (tab, event) => {
      console.log(tab.props.name);
      reactiveData.date = "";
      reactiveData.filterData = {
        status: tab.props.name,
        keyWord: "",
        page: 1,
        pageSize: 20,
        initiatorStartTime: null, // 发起开始时间
        initiatorEndTime: null, // 发起结束时间
        manageStartTime: null, // 处理开始时间
        manageEndTime: null, // 处理结束时间
        processDefinitionKey: "",
      };
      if (tab.props.name === "ACTIVE") {
        reactiveData.filterData.status = "ACTIVE";
        reactiveData.label = "发起时间";
        getList(reactiveData.filterData);
      } else {
        reactiveData.filterData.status = "COMPLETED";
        getList(reactiveData.filterData);
        reactiveData.label = "处理时间";
      }
    };
    const getList = (val) => {
      api.myStarted.MYSTARTED_LIST(val).then((res) => {
        if (res.code === 0) {
          reactiveData.listData = res.data.list;
          reactiveData.total = res.data.total;
        }
      });
    };
    const auditOperation = (row) => {
      handlTaskId(row?.currentTask?.taskId, row, 1);
    };
    const handlTaskId = (id, val, num) => {
      api.approval.APPROVAL_FORM({ taskId: id }).then((res) => {
        if (res.code === 0) {
          if (num === 1) {
            const currentTask = {
              form: res.data,
              taskId: id,
            };
            approvalRef.value.open(currentTask, val);
          } else {
            var form = {
              result: {
                type: String,
                value: 'REPEAL',
              },
            };
            // form.result.value = "REPEAL";
            var dataList = {
              taskId: id,
              form: form,
            };
            api.approval.APPROVAL_SUBMIT(dataList).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "撤销成功",
                });
                refreshList();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          }
        }
      });
    };
    const cancelOperation = (row) => {
      currentInstance.proxy
        .alertBox({ title: "撤销审批", message: "是否确认取消？" })
        .then(() => {
          handlTaskId(row?.currentTask?.taskId, row, 2);
        });
    };
    const refreshList = () => {
      getList(reactiveData.filterData);
    };
    onMounted(() => {
      getList(reactiveData.filterData);
    });

    // 排序
    const handlSort = (row) => {
      if (row.column) {
        if (row.column.label === "发起时间") {
          switch (row.order) {
            case "ascending":
              reactiveData.filterData.initiatorStart = "asc";
              break;
            case "descending":
              reactiveData.filterData.initiatorStart = "desc";
              break;
          }
          reactiveData.filterData.manageStartEnd = "";
        }

        if (row.column.label === "最后处理时间") {
          switch (row.order) {
            case "ascending":
              reactiveData.filterData.manageStartEnd = "asc";
              break;
            case "descending":
              reactiveData.filterData.manageStartEnd = "desc";
              break;
          }
          reactiveData.filterData.initiatorStart = "";
        }
      }
      getList(reactiveData.filterData);
    };
    return {
      ...toRefs(reactiveData),
      approvalRef,
      cellStyle,
      rowClick,
      getList,
      refreshList,
      handleClick,
      auditOperation,
      cancelOperation,
      handlDate,
      handlSearch,
      handlReact,
      handlSort,
    };
  },
};
</script>

<style>
</style>
